//
//  DDLocate.m
//  DDMates
//
//  Created by ShawnMa on 12/27/11.
//  Copyright (c) 2011 TelenavSoftware, Inc. All rights reserved.
//

#import "TSLocation.h"
#import "SBJson.h"

@implementation TSLocation

+ (TSLocation *)sharedInstance{
    static TSLocation *_tsLocation = nil;
    if (_tsLocation == nil) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _tsLocation = [[TSLocation alloc] init];
            [_tsLocation initLocationData];
        });
    }
    return _tsLocation;
}


- (instancetype)init {
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)initLocationData {
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    NSString *citiesList = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"cities.json" ofType:nil] encoding:NSUTF8StringEncoding error:nil];
    NSArray *data = [parser objectWithString:citiesList];
    
    self.localLocationArray = [NSArray arrayWithObject:data];
    self.provinces = self.localLocationArray[0];
    self.cities = [self getArrayByComponent:1];
    self.towns = [self getArrayByComponent:2];
    self.villages = [self getArrayByComponent:3];
    self.selectFirstRow = 0;
    self.selectSecondRow = 0;
    self.selectThirdRow = 0;
    self.selectForthRow = 0;
}

#pragma mark - Public
- (NSArray *)getArrayByComponent:(NSInteger)component {
    NSMutableArray *tempArr = [NSMutableArray array];
    if (component == 0) {
        tempArr = [self.localLocationArray[self.selectFirstRow] objectForKey:@"value"];
    } else if (component == 1) {
        tempArr = [self.provinces[self.selectFirstRow] objectForKey:@"value"];
    } else if (component == 2) {
        tempArr = [self.cities[self.selectSecondRow] objectForKey:@"value"];
    } else if (component == 3) {
        tempArr = [self.towns[self.selectThirdRow] objectForKey:@"value"];
    }
    return tempArr;
}

- (void)refreshLocateInfo {
    self.province = [[self.provinces objectAtIndex:self.selectFirstRow] objectForKey:@"name"];
    self.city = [[self.cities objectAtIndex:self.selectSecondRow] objectForKey:@"name"];
    self.town = [[self.towns objectAtIndex:self.selectThirdRow] objectForKey:@"name"];
    self.village = [self.villages objectAtIndex:self.selectForthRow];
}

- (void)clearData {
    self.province = nil;
    self.city = nil;
    self.town = nil;
    self.village = nil;
}

- (BOOL)hasData {
    return self.province.length > 0 && self.city.length > 0 && self.town.length > 0 && self.village.length > 0;
}

@end
